package network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;


public class GameFinder {
	private static Socket s;
	public static ArrayList<GameInfo> findGames(){
		ArrayList<GameInfo> availableGames = new ArrayList<GameInfo>();
		String[] ipsInLab = {"bill","shadowfax","gimli","legolas","boromir","aragorn","pippin","merry","sam","frodo","gandalf"};
		for (String ip : ipsInLab){
			String response = sendMessage(ip,"pk_host_request:\n");
			System.out.println("Response:"+response);
			if (response.length() >= 4&&response.substring(0,4).equals("True")){
				System.out.println("Game found @ "+ip);
				String details = response.substring(5);
				GameInfo game = new GameInfo(ip,details);
				availableGames.add(game);
			}
		}
		return availableGames;
	}
	public static int joinGame(GameInfo game, String username){
		String playerNum = sendMessage(game.getIP(),"pk_join_game:"+username+"\n");
		System.out.println("PlayerNum:"+playerNum);
		if (playerNum.length() > 0){
			playerNum = playerNum.substring(playerNum.indexOf(":") + 1);
			playerNum = playerNum.replace("\n", "");
		}
		else{
			return -1;
		}
		System.out.println("PlayerNum:"+playerNum);
		return Integer.parseInt(playerNum);
	}
	public static String sendMessage(String ip, String message) {
		String response = "";
		
		try {
			Thread.sleep(10);
			s = new Socket();
			System.out.println("IP:"+ip);
			s.connect(new InetSocketAddress(ip, 8888), 500);
			//Scanner in = new Scanner(System.in);
			PrintWriter writer = new PrintWriter(s.getOutputStream());
			StringBuilder msg = new StringBuilder();
			//System.out.println("Begin message; type ! by itself when done");
			
			msg.append(message);
			writer.print(msg.toString());
			writer.flush();
			System.out.println("Message Sent");
			BufferedReader responses = new BufferedReader(new InputStreamReader(s.getInputStream()));
			int counter = 0;
			while (!responses.ready()&&counter < 500000){counter++;}
			
			while (responses.ready()){
				System.out.println("Read lines");
				response = responses.readLine() + "\n";
			}
			System.out.println("hit here");
			
		} catch (IOException  ioe) {
			System.out.println("Game not available @:"+ip);
			//HOST UNREACHABLE
		} catch (InterruptedException ioe){
			ioe.printStackTrace();
		}finally {
		
			try {
				if (s != null) {s.close();}
			} catch (IOException ioe) {
				System.out.println("error closing socket");
			}
		}
		return response;
	}
}
